package com.jysz.certificate.service.system;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.system.MenuDao;
import com.jysz.certificate.persistence.dao.system.OperDao;
import com.jysz.certificate.persistence.dao.system.RoleDao;
import com.jysz.certificate.persistence.dao.system.UserDao;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.model.system.Menu;
import com.jysz.certificate.persistence.model.system.Role;
import com.jysz.certificate.persistence.model.system.RoleOperRef;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.utils.CommonUtil;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;
import com.jysz.webcore.ssh.service.EntityService;

/**
 * 权限管理
 */
@Service
public class RoleService extends EntityService<Role, Long, RoleDao>{
	
	@Resource
	private RoleDao roleDao;
	@Resource
	private UserDao userDao;
	@Resource
	private OperDao operDao;
	@Resource
	private MenuDao menuDao;

	@Override
	public RoleDao getEntityDao() {
		return roleDao;
	}

	//角色查询(列表)
	public Page<Role> findPage(Role search, int pageNo, int pageSize) {
		Criteria criteria = roleDao.createCriteria();
		criteria.addOrder(Order.asc("initialize"));
		return this.findPage(criteria, pageNo, pageSize);
	}

	//授权时获得所有权限
	public List<Menu> findOpers(){
		
		List<Menu> list=menuDao.findTopMenus();
		return list;
	}
	
	public void save(Role entity,String userIds,String codes){
		buildUserAndOper(entity, userIds, codes);
		super.save(entity);
	}
	
	//检查用户是否有该权限
	public boolean checkPermission(User user,String code){
		User u=userDao.find(user.getId());
		if(u!=null&&u.getPost().compareTo(PostType.Admin)==0)
			return true;
		if(u==null||CommonUtil.isEmpty(code)||u.getRoles()==null||u.getRoles().size()==0)
			return false;
		boolean f=operDao.checkPermission(u, code);
		return f;
		
	}
	
	//构建角色所包含的用户和权限
	private void buildUserAndOper(Role entity,String userIds,String codes){
		if(entity==null)
			return;
		if(CommonUtil.isNotEmpty(userIds)){
			Long uids[]=CommonUtil.getLongArrayFromIds(userIds, ",");
			Set<User> users=new HashSet<User>();
			for(Long uid:uids){
				users.add(userDao.find(uid));
			}
			entity.setUsers(users);
		}
		if(CommonUtil.isNotEmpty(codes)){
			String cds[]=codes.split(",");
			entity.getRoleOperRefList().clear();
			RoleOperRef tmp=null;
			for(String code:cds){
				tmp=new RoleOperRef();
				tmp.setRole(entity);
				tmp.setOper(operDao.findByCode(code));
				entity.getRoleOperRefList().add(tmp);
			}
		}
		
		
	}
}
